/**
 * Copyright (C) 2010 Cloudfarming <info@cloudfarming.nl>
 *
 * Licensed under the Eclipse Public License - v 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.eclipse.org/legal/epl-v10.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.cloudfarming.client.sensor.area;

import java.util.List;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import nl.cloudfarming.client.model.CommonModelService;
import nl.cloudfarming.client.model.Plot;
import nl.cloudfarming.client.model.SensorData;
import nl.cloudfarming.client.model.SensorDataFile;
import nl.cloudfarming.client.model.SensorRun;

/**
 *
 * @author Timon Veenstra
 */
public class SensorAreaService extends CommonModelService {

    @Override
    protected String getModuleName() {
        return SensorAreaModule.MODULE_NAME;
    }

    public void persist(List<SensorData> sensorData){
        startTransaction();
        for (SensorData sd : sensorData){
            mergeSensorData(sd);
        }
        commit();
    }

    public SensorRun findSensorRunForPlotAndFile(Plot plot, SensorDataFile<?> sensorDataFile) {
        startTransaction();
        Query query = getEntityManager().createQuery(
                "select sr from SensorRun sr "
                + "where sr.sensorDataFile = :sensorDataFile "
                + "and sr.plot = :plot");
        query.setParameter("sensorDataFile", sensorDataFile);
        query.setParameter("plot", plot);
        try {
            return (SensorRun) query.getSingleResult();
        } catch (NoResultException ner) {
            return null;
        }
    }

    public List<SensorData> findSensorDataForPlot(Plot plot) {
        startTransaction();
        Query query = getEntityManager().createQuery(
                "select sd from SensorData sd "
                + "where sd.sensorRun in "
                + "(select sr from SensorRun sr, SensorDataFile sdf "
                + "where sdf = sr.sensorDataFile "
                + "and sr.plot = :plot)");
        query.setParameter("plot", plot);
        try {
            return (List<SensorData>) query.getResultList();
        } catch (NoResultException ner) {
            return null;
        }
    }
}
